/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.datatheorem.ohos.trustkit.utils;


import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.UUID;

/**
 * When TrustKit sends a report, it also sends a randomly-generated identifier to uniquely identify
 * a specific App install (ie. an instance of the App running on a specific device). It is the least
 * intrusive way to detect reports coming from the same device.
 */
public class VendorIdentifier {

    private static final String TRUSTKIT_VENDOR_ID = "TRUSTKIT_VENDOR_ID";

    public static String getOrCreate( Context appContext) {
        Preferences trustKitSharedPreferences =  (new DatabaseHelper(appContext)).getPreferences(appContext.getBundleName());
        // We store the vendor ID in the App's preferences
        String appVendorId = trustKitSharedPreferences.getString(TRUSTKIT_VENDOR_ID, "");
        if (appVendorId.equals("")) {
            // First time the App is running: generate and store a new vendor ID
            TrustKitLog.i("Generating new vendor identifier...");
            appVendorId = UUID.randomUUID().toString();
            trustKitSharedPreferences.putString(TRUSTKIT_VENDOR_ID, appVendorId);
            trustKitSharedPreferences.flushSync();
        }
        return appVendorId;
    }
}

